<template>
  <div id="login">
    <div class="loginfrom">
      <!-- 左侧背景展示区 -->
      <div class="left-section">
        <div class="left-content">
          <h1 class="platform-title">农产品质量追溯平台</h1>
          <p class="slogan">保障食品安全 · 追溯源头质量</p>
          <ul class="colum">
            <li>
              <img src="@/assets/images/right.png" alt="√">
              <div>
                <h3>全程可追溯</h3>
                <p>从农田到餐桌，全程记录农产品生产流通信息</p>
              </div>
            </li>
            <li>
              <img src="@/assets/images/right.png" alt="√">
              <div>
                <h3>数据实时监控</h3>
                <p>实时监控农产品质量，确保数据真实可靠</p>
              </div>
            </li>
            <li>
              <img src="@/assets/images/right.png" alt="√">
              <div>
                <h3>质量安全保障</h3>
                <p>严格的质量管理体系，确保食品安全</p>
              </div>
            </li>
          </ul>
        </div>
      </div>

      <!-- 右侧登录表单区 -->
      <div class="right-section">
        <div class="right-content">
          <div class="platform-header">
            <img 
              src="@/assets/images/website.ico" 
              alt="🍃" 
              class="platform-logo"
            >
            <span class="platform-name">农产品溯源平台</span>
          </div>

          <!-- 登录/注册标签 -->
          <div class="tab-group">
            <span  class="tab"  :class="{ active: activeTab === 'login' }"  @click="switchTab('login')">登录</span>
            <span class="tab" :class="{ active: activeTab === 'register' }" @click="switchTab('register')">注册</span>
          </div>

          <!-- 登录表单 -->
          <form class="login-form" v-if="activeTab === 'login'">
            <div class="form-group">
              <input 
                type="text" 
                placeholder="用户名/手机号" 
                class="form-input"
                v-model="loginForm.username"
              >
            </div>
            <div class="form-group">
              <input 
                type="password" 
                placeholder="密码" 
                class="form-input"
                v-model="loginForm.password"
                @keyup.enter="handleLogin"
              >
            </div>

            <div class="form-group" v-if="captchaEnabled">
              <div style="display: flex; align-items: center; gap: 10px;">
                <input 
                  type="text" 
                  placeholder="验证码" 
                  class="form-input"
                  style="width: 63%; margin-bottom: 0;"
                  v-model="loginForm.code"
                  @keyup.enter="handleLogin"
                >
                <img :src="codeUrl" @click="getCode" class="login-code-img" style="height: 40px; cursor: pointer;"/>
              </div>
            </div>

            <div class="remember-row">
              <label class="remember-label">
                <input type="checkbox" class="remember-check" v-model="loginForm.rememberMe">
                <span class="check-icon"></span>
                记住我
              </label>
              <a href="" class="forget-link">忘记密码？</a>
            </div>

            <button @click.prevent="handleLogin" type="submit" class="login-btn" :disabled="loading">
              <span v-if="!loading">立即登录</span>
              <span v-else>登 录 中...</span>
            </button>

            <!-- 其他登录方式 -->
            <div class="other-login">
              <span class="separator">其他登录方式</span>
              <div class="login-icons">
                <a href="#" class="icon-item wechat">微信</a>
                <a href="#" class="icon-item alipay">支付宝</a>
                <a href="#" class="icon-item enterprise">企业微信</a>
              </div>
            </div>

            <!-- 底部协议 -->
            <div class="policy-group">
              <a href="#" class="policy-link">隐私政策</a>
              <span class="divider">|</span>
              <a href="#" class="policy-link">用户协议</a>
            </div>
          </form>

          <!-- 注册表单 -->
          <form class="login-form" v-if="activeTab === 'register'">
            <div class="form-group">
              <input 
                type="text" 
                placeholder="用户名" 
                class="form-input"
                v-model="registerForm.username"
              >
            </div>
            <div class="form-group">
              <input 
                type="text" 
                placeholder="手机号" 
                class="form-input"
                v-model="registerForm.phonenumber"
              >
            </div>
            <div class="form-group">
              <input 
                type="text" 
                placeholder="微信号" 
                class="form-input"
                v-model="registerForm.wechatNumber"
              >
            </div>
            <div class="form-group">
              <input 
                type="password" 
                placeholder="密码" 
                class="form-input"
                v-model="registerForm.password"
                @keyup.enter="handleRegisterSubmit"
              >
            </div>
            <div class="form-group">
              <input 
                type="password" 
                placeholder="确认密码" 
                class="form-input"
                v-model="registerForm.confirmPassword"
                @keyup.enter="handleRegisterSubmit"
              >
            </div>
            
            <div class="form-group">
              <div class="company-status-container">
                <label class="radio-label">
                  <input 
                    type="radio" 
                    name="companyStatus"
                    class="radio-input"
                    value="否"
                    v-model="registerForm.companyStatus"
                  >
                  <span class="radio-custom"></span>
                  <span class="radio-text">个人用户</span>
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    name="companyStatus"
                    class="radio-input"
                    value="是"
                    v-model="registerForm.companyStatus"
                  >
                  <span class="radio-custom"></span>
                  <span class="radio-text">企业用户</span>
                </label>
              </div>
            </div>

            <div class="form-group" v-if="captchaEnabled">
              <div style="display: flex; align-items: center; gap: 10px;">
                <input 
                  type="text" 
                  placeholder="验证码" 
                  class="form-input"
                  style="width: 63%; margin-bottom: 0;"
                  v-model="registerForm.code"
                  @keyup.enter="handleRegisterSubmit"
                >
                <img :src="codeUrl" @click="getCode" class="login-code-img" style="height: 40px; cursor: pointer;"/>
              </div>
            </div>

            <button @click.prevent="handleRegisterSubmit" type="submit" class="login-btn" :disabled="registerLoading">
              <span v-if="!registerLoading">立即注册</span>
              <span v-else>注 册 中...</span>
            </button>

            <!-- 底部协议 -->
            <div class="policy-group">
              <a href="#" class="policy-link">隐私政策</a>
              <span class="divider">|</span>
              <a href="#" class="policy-link">用户协议</a>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCodeImg, register } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'
import usePermissionStore from '@/store/modules/permission'
import { isHttp } from '@/utils/validate'
import { ElMessage } from 'element-plus'
const title = import.meta.env.VITE_APP_TITLE
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// 表单数据
const loginForm = reactive({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
})

// 注册表单数据
const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  phonenumber: "",
  wechatNumber: "",
  companyStatus: "否", // 是否为企业用户，"否"表示个人用户，"是"表示企业用户
  code: "",
  uuid: ""
})

const activeTab = ref('login') // 登录/注册标签
const loading = ref(false)
const registerLoading = ref(false)
const codeUrl = ref("")
const captchaEnabled = ref(true)
const redirect = ref(undefined)

// 监听路由变化
watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

// 切换标签
function switchTab(tab) {
  activeTab.value = tab
}

// 登录处理
function handleLogin() {
  // 简单的表单验证
  if (!loginForm.username) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!loginForm.password) {
    ElMessage.warning('请输入密码')
    return
  }
  if (captchaEnabled.value && !loginForm.code) {
    ElMessage.warning('请输入验证码')
    return
  }

  loading.value = true
  
  // 记住密码处理
  if (loginForm.rememberMe) {
    Cookies.set("username", loginForm.username, { expires: 30 })
    Cookies.set("password", encrypt(loginForm.password), { expires: 30 })
    Cookies.set("rememberMe", loginForm.rememberMe, { expires: 30 })
  } else {
    Cookies.remove("username")
    Cookies.remove("password")
    Cookies.remove("rememberMe")
  }

  // 调用登录方法
  userStore.login(loginForm).then(() => {
    // 获取用户信息
    return userStore.getInfo()
  }).then(() => {
    // 生成权限路由
    return usePermissionStore().generateRoutes()
  }).then(accessRoutes => {
    // 添加权限路由
    accessRoutes.forEach(route => {
      if (!isHttp(route.path)) {
        router.addRoute(route)
      }
    })
    
    const query = route.query
    const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
      if (cur !== "redirect") {
        acc[cur] = query[cur]
      }
      return acc
    }, {})
    
    // 根据权限决定跳转路径
    const roles = userStore.roles
    console.log('User roles:', JSON.parse(JSON.stringify(roles)))
    
    if(roles.includes('admin')){
      console.log('admin')
      router.replace({ 
        path: '/', 
        query: otherQueryParams
      }).then(() => {
        console.log('Navigation admin completed')
      }).catch(err => {
        console.error('Navigation error:', err)
      })
    }else{
      router.replace({ 
        path: '/ncpsy', 
        query: otherQueryParams
      }).then(() => {
        console.log('Navigation completed')
      }).catch(err => {
        console.error('Navigation error:', err)
      })
    }
  }).catch((err) => {
    console.error('Login error:', err)
    loading.value = false
    // 重新获取验证码
    if (captchaEnabled.value) {
      getCode()
    }
  })
}

// 注册处理
function handleRegisterSubmit() {
  // 表单验证
  if (!registerForm.username) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!registerForm.password) {
    ElMessage.warning('请输入密码')
    return
  }
  if (registerForm.password !== registerForm.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }
  if (captchaEnabled.value && !registerForm.code) {
    ElMessage.warning('请输入验证码')
    return
  }

  registerLoading.value = true
  
  // 调用注册API
  register(registerForm).then(res => {
    ElMessage.success(`恭喜您，账号 ${registerForm.username} 注册成功！`)
    // 注册成功后切换到登录标签
    activeTab.value = 'login'
    // 清空注册表单
    registerForm.username = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
    registerForm.phonenumber = ''
    registerForm.wechatNumber = ''
    registerForm.companyStatus = "否"
    registerForm.code = ''
  }).catch(err => {
    console.error('Register error:', err)
    ElMessage.error('注册失败，请重试')
  }).finally(() => {
    registerLoading.value = false
  })
}

// 获取验证码
function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img
      loginForm.uuid = res.uuid
      registerForm.uuid = res.uuid
    }
  })
}

// 获取cookie中的记住信息
function getCookie() {
  const username = Cookies.get("username")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  
  if (username) loginForm.username = username
  if (password) loginForm.password = decrypt(password)
  if (rememberMe) loginForm.rememberMe = Boolean(rememberMe)
}

// 初始化
getCode()
getCookie()
</script>

<style scoped>
.login-code-img {
  height: 40px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

#login {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('@/assets/images/bgc.png') no-repeat center center;
  background-size: cover;
}

.loginfrom {
  width: 1200px;
  height: 700px;
  display: flex;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
}

/* 左侧背景区样式 */
.left-section {
  flex: 1;
  background: url('@/assets/images/login.png') no-repeat center center;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  padding: 40px;
}

.left-content {
  max-width: 420px;
}

.platform-title {
  font-size: 36px;
  font-weight: 700;
  margin-bottom: 24px;
  line-height: 1.2;
}

.slogan {
  font-size: 18px;
  margin-bottom: 36px;
  opacity: 0.9;
  line-height: 1.6;
}

.colum{
  list-style: none;
}
.colum li{
  display: flex;
  align-items: center;
  margin-bottom: 20px; 
}
.colum li img{
  width: 20px;
  margin-bottom: 20px;
}
.colum li div{
  display: inline-block;
}

.colum li div h3 {
  display: flex;
  font-size: 18px;
  margin: 0 0 8px 0;
  font-weight: 600;
}


/* 右侧表单区样式 */
.right-section {
  width: 450px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-content {
  width: 80%;
}

.platform-header {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
}

.platform-logo {
  width: 40px;
  height: 40px;
  margin-right: 12px;
}

.platform-name {
  font-size: 22px;
  font-weight: 600;
  color: #333;
}

.tab-group {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 36px;
}

.tab {
  flex: 1;
  text-align: center;
  font-size: 16px;
  padding: 12px 0;
  color: #999;
  cursor: pointer;
  transition: all 0.3s;
}

.tab.active {
  color: #009639;
  border-bottom: 2px solid #009639;
  font-weight: 600;
}

.form-group {
  margin-bottom: 24px;
}

.form-input {
  width: 90%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
  color: black;
}

.form-input:focus {
  border-color: #009639;
}

.remember-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  font-size: 14px;
  color: #666;
}

.remember-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.remember-check {
  display: none;
}

.check-icon {
  width: 16px;
  height: 16px;
  border: 1px solid #ccc;
  border-radius: 2px;
  margin-right: 8px;
  position: relative;
  flex-shrink: 0;
}

.remember-check:checked + .check-icon::after {
  content: '✓';
  position: absolute;
  top: -1px;
  left: 3px;
  font-size: 12px;
  color: #009639;
}

.forget-link {
  color: #009639;
  text-decoration: none;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background-color: #009639;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 24px;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #007a2f;
}

.other-login {
  text-align: center;
  margin-bottom: 24px;
}

.separator {
  display: block;
  margin-bottom: 12px;
  font-size: 14px;
  color: #999;
  position: relative;
}

.separator::before,
.separator::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 30%;
  height: 1px;
  background-color: #eee;
}

.separator::before {
  left: 0;
}

.separator::after {
  right: 0;
}

.login-icons {
  display: flex;
  justify-content: center;
  gap: 32px;
}

.icon-item {
  text-decoration: none;
  color: #333;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 14px;
  transition: color 0.3s;
}

.icon-item:hover {
  color: #009639;
}

.icon-item i {
  font-size: 24px;
  margin-bottom: 4px;
}

.policy-group {
  text-align: center;
  font-size: 14px;
  color: #999;
}

.policy-link {
  color: #009639;
  text-decoration: none;
  margin: 0 6px;
}

.divider {
  color: #ccc;
}

/* 用户类型选择样式 */
.company-status-container {
  display: flex;
  gap: 20px;
  padding: 5px 0;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.radio-input {
  display: none;
}

.radio-custom {
  width: 16px;
  height: 16px;
  border: 2px solid #ddd;
  border-radius: 50%;
  margin-right: 8px;
  position: relative;
  transition: all 0.3s;
}

.radio-text {
  font-weight: 500;
}

.radio-input:checked + .radio-custom {
  border-color: #009639;
}

.radio-input:checked + .radio-custom::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 8px;
  height: 8px;
  background-color: #009639;
  border-radius: 50%;
}
</style>